package com.xianggu.trafficLimiter.impl;

import com.xianggu.trafficLimiter.TrafficLimiter;

import java.util.concurrent.atomic.AtomicLong;

/**
 * @author chengjy
 * @date 2025/3/25
 */

public class CounterBucketLimiter implements TrafficLimiter {

    private long timeStamp = System.currentTimeMillis();
    private AtomicLong count = new AtomicLong(0);// 当前请求数
    private long max = 10; // 每秒中最大QBS

    private long interval = 1000L; // 时间窗口时长


    @Override
    public synchronized boolean limit() {
        // 获取上次请求与本次请求的间隔，如果间隔小于1s，则请求数+1，否则重置请求数并记录当前时间戳
        long now = System.currentTimeMillis();
        if(now < timeStamp + interval){
            if(count.get() + 1 > max){
//                System.out.println("拦截访问 当前请求数："+count.get());
                return true;
            }
            count.compareAndSet(count.get(), count.get() + 1);
            return false;
        }else{
            // 只有大于时间窗口或者时间戳小于当前时间戳，才重置请求数，重置访问时间
            timeStamp = now;
            count.set(1);
            return false;
        }

//        long elapsed = now - timeStamp;
//        timeStamp = now;// 重置请求时间
//
//        if(elapsed > 1000){
//            count.set(1);
//            return false;
//        } else if(count.get() + 1 > max){
//            System.out.println("拦截访问 当前请求数："+count.get());
//            return true;
//        }else{
//            count.compareAndSet(count.get(), count.get() + 1);
//            return false;
//        }
    }
}
